<template>
  <div class="basic-form">
    <cus-form :nodes="nodes" ref="formRef" :data="data" />

    <div class="btns">
      <el-button size="medium" @click="close">取消</el-button>
      <el-button size="medium" type="primary" :loading="loading" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, inject, computed, watch } from "vue";
import { useStore } from "vuex";
import $ from "$";
import { ElMessage } from "element-plus";
import store from "./../store";

export default {
  setup() {
    let baseStore = useStore();

    let currentIndex = computed(() => store.state.currentIndex);

    let close = inject("close");

    let data = computed<any>(() => store.state.courseInfo);

    let formRef = ref();

    let userId = baseStore.getters.userInfo.user.id;
    let subjectDefault = [
      baseStore.getters.subject.parentCode,
      baseStore.getters.subject.code,
    ];

    let nodes = ref([
      {
        label: "课程名称",
        type: "input",
        key: "courseName",
        rule: [{ required: true, message: "请输入课程名称！" }],
      },
      {
        label: "学科",
        type: "cascader",
        key: "subjectId",
        url: "/permission/user/userDataSubjects",
        // default: subjectDefault,
        valueKey: "code",
        rule: [{ required: true, message: "请选择学科！" }],
        change: (v) => __subjectChange(v),
      },
      {
        label: "班型",
        type: "select",
        key: "courseTypeId",
        options: [],
        rule: [{ required: true, message: "请选择班型！" }],
      },
      {
        label: "年级",
        type: "select",
        key: "gradeId",
        options: [],
      },
      {
        label: "年份",
        type: "select",
        key: "year",
        options: [],
      },
      {
        label: "学期",
        type: "select",
        key: "semesterId",
        options: [],
      },
      {
        label: "课程封面",
        type: "image",
        key: "imgPath",
        limit: 1,
      },
    ]);

    const __subjectChange = (val, isInit = false) => {
      $.http
        .post("/permission/user/userDataRules", { userId, subjectCode: val[1] })
        .then((res: any) => {
          nodes.value[2].options = res.json.courseTypes;
          nodes.value[3].options = res.json.grades;
          nodes.value[4].options = res.json.years;
          nodes.value[5].options = res.json.terms;
          if (!isInit) {
            formRef.value.formGroup.courseTypeId &&
              (formRef.value.formGroup.courseTypeId = null);
            formRef.value.formGroup.gradeId &&
              (formRef.value.formGroup.gradeId = null);
            formRef.value.formGroup.year &&
              (formRef.value.formGroup.year = null);
            formRef.value.formGroup.semesterId &&
              (formRef.value.formGroup.semesterId = null);
          }
        });
    };
    __subjectChange(subjectDefault, true);

    let loading = ref(false);
    const save = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          valid.subjectId = Array.isArray(valid.subjectId)
            ? valid.subjectId[1]
            : valid.subjectId;
          let res = await $.http.json(
            `/course/${data.value.id ? "modify" : "add"}`,
            {
              ...valid,
              ...(data.value.id
                ? { id: data.value.id }
                : { courseIndexNum: 0 }),
            }
          );
          ElMessage[res.result ? "success" : "warning"](res.msg);
          loading.value = false;
          store.commit("set_course_info", res.json);
          store.commit("set_current_index", 1);
          store.state.completeIndex === -1 &&
            store.commit("set_complete_index", 0);
        }
      });
    };
    
    return { nodes, close, formRef, save, loading, data };
  },
};
</script>
<style lang="scss" scoped>
.basic-form {
  padding: 50px 300px;
  height: calc(100vh - 180px);
  overflow: auto;
  background: #fff;
  .btns {
    text-align: center;
  }
}
</style>